package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.app.func.MyAllWindowFunction;
import com.atguigu.bean.HomeCourseDetailBean;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.MyClickHouseUtil;
import com.atguigu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws0203HomeCourseDetailWindow {
    public static void main(String[] args) throws Exception {
        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
//        tableEnv.getConfig().setIdleStateRetention(Duration.ofSeconds(18*60+5));
        //  状态后端设置
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");
        //2.从kafka DWD读取dwd_traffic_page_view的数据并生成watermark
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_traffic_page_view", "traffic_source"), WatermarkStrategy.<String>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<String>() {
            @Override
            public long extractTimestamp(String s, long l) {
                JSONObject jsonObject = JSON.parseObject(s);
                return jsonObject.getLong("ts");
            }
        }), "kafka-source");
        //3.筛选出首页和商品详情页的数据并将数据转换为JSONOBJECT
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                JSONObject page = jsonObject.getJSONObject("page");
                String pageId = page.getString("page_id");
                if ("home".equals(pageId) || "course_detail".equals(pageId)) {
                    collector.collect(jsonObject);
                }
            }
        });
        //4.按照mid keyby 并将数据转换为JavaBean
        SingleOutputStreamOperator<HomeCourseDetailBean> homeCourseDetailBeanDS = jsonObjDS.keyBy(r -> r.getJSONObject("common").getString("mid")).flatMap(new RichFlatMapFunction<JSONObject, HomeCourseDetailBean>() {
            private ValueState<String> homeState;
            private ValueState<String> detailState;


            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1)).build();
                ValueStateDescriptor<String> homeDesc = new ValueStateDescriptor<>("home-state", String.class);
                homeDesc.enableTimeToLive(ttlConfig);
                homeState = getRuntimeContext().getState(homeDesc);

                ValueStateDescriptor<String> detailDesc = new ValueStateDescriptor<>("detail-state", String.class);
                detailDesc.enableTimeToLive(ttlConfig);
                detailState = getRuntimeContext().getState(detailDesc);
            }

            @Override
            public void flatMap(JSONObject jsonObject, Collector<HomeCourseDetailBean> collector) throws Exception {
                String lastHomeDt = homeState.value();
                String lastDetailDt = detailState.value();
                Long ts = jsonObject.getLong("ts");
                String curDt = DateFormatUtil.toYmdHms(ts);
                String pageId = jsonObject.getJSONObject("page").getString("page_id");
                long homeCount = 0L;
                long detailCount = 0L;
                if ("home".equals(pageId)) {
                    if (lastHomeDt == null || !lastHomeDt.equals(curDt)) {
                        homeCount = 1L;
                        homeState.update(curDt);
                    }
                } else if ("course_detail".equals(pageId)) {
                    if (lastDetailDt == null || !lastDetailDt.equals(curDt)) {
                        detailCount = 1L;
                        detailState.update(curDt);
                    }

                }
                if (homeCount == 1L || detailCount == 1L){
                    collector.collect(new HomeCourseDetailBean("","",homeCount,detailCount,0L));
                }
            }
        });

        //5.开窗 聚合
        SingleOutputStreamOperator<HomeCourseDetailBean> reduceDS = homeCourseDetailBeanDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<HomeCourseDetailBean>() {
            @Override
            public HomeCourseDetailBean reduce(HomeCourseDetailBean value1, HomeCourseDetailBean value2) throws Exception {
                value1.setHomeCount(value1.getHomeCount()+value2.getHomeCount());
                value1.setGoodDetailCount(value1.getGoodDetailCount()+value2.getGoodDetailCount());
                return value1;
            }
        }, new MyAllWindowFunction<HomeCourseDetailBean, TimeWindow>());
        //6.写出
        reduceDS.print("reduceDS>>>>>");
        reduceDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_home_course_detail_window values (?,?,?,?," +
                "?)"));
        env.execute();


    }
    }

